package com.bjpowernode.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.constants.Constant;
import com.bjpowernode.constants.RedisKey;
import com.bjpowernode.constants.enums.Code;
import com.bjpowernode.web.resp.ResponseObj;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 麦翔盛
 * @ClassName: TokenInterceptor
 * @Package: com.bjpowernode.web.interceptor
 * @description: token拦截器
 * @date 2022/5/24 21:42
 */
public class TokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean auth = false;

        //放行OPTIONAL的请求
        if (Constant.METHOD_OPTIONS.equals(request.getMethod())){
            return true;
        }

        //从请求头中取出
        String authorization = request.getHeader("Authorization");

        //判断不为空 而且 以Bearer开头
        if (StringUtils.isNotBlank(authorization) && authorization.startsWith(Constant.HEADER_BEARER)){
            //取出token
            String token = authorization.substring(Constant.TOKEN_START_INDEX);
            //对token进行判空
            if (StringUtils.isBlank(token)){
                return false;
            }
            //从redis中取出对应的数据
            String tokenKey = RedisKey.ACCESS_TOKEN + token;
            //如果有存的这个值
            if (redisTemplate.hasKey(tokenKey)){
                //绑定数据
                BoundHashOperations<String, Object, Object> opts =
                        redisTemplate.boundHashOps(tokenKey);
                //获取uid
                String redisUid = (String) opts.get("uid");
                String headerUid = request.getHeader("uid");
                //验证redis中的uid 和 请求头中的uid是否相同
                if (StringUtils.isNoneBlank(redisUid,headerUid) && StringUtils.equals(redisUid,headerUid)){
                    auth = true;
                }
            }

        }

        //判断是否匹配 如果不匹配就返回错误信息给前端
        if (!auth){
            //设置返回给前端的数据是json
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();

            //创建返回json
            ResponseObj responseObj = ResponseObj.error(Code.REAL_NAME_VERIFIED_FAIL);
            String result = JSONObject.toJSONString(responseObj);

            out.print(result);
            out.flush();
            out.close();


        }

        return auth;
    }
}
